package router

import (
	"context"
	"errors"
	"gin-gateway/core/init"
	"log"
	"net/http"
	"time"
)

var HttpsSrvHandler *http.Server

func HttpsProxyServerRun() {
	HttpsSrvHandler = &http.Server{
		Addr:           Init.GetStringConf("proxy.https.addr"),
		Handler:        InitProxyRouter(),
		ReadTimeout:    time.Duration(Init.GetIntConf("proxy.https.read_timeout")) * time.Second,
		WriteTimeout:   time.Duration(Init.GetIntConf("proxy.https.write_timeout")) * time.Second,
		MaxHeaderBytes: 1 << uint(Init.GetIntConf("proxy.https.max_header_bytes")),
	}
	log.Printf("[INFO] HttpsProxyServerRun %s\n", Init.GetStringConf("proxy.https.addr"))
	if err := HttpsSrvHandler.ListenAndServeTLS("./conf/cert_file/server.crt", "./conf/cert_file/server.key"); err != nil && !errors.Is(err, http.ErrServerClosed) {
		log.Fatalf("[ERROR] HttpsProxyServerRun %s err:%v\n", Init.GetStringConf("proxy.https.addr"), err)
	}
}

func HttpsProxyServerStop() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := HttpsSrvHandler.Shutdown(ctx); err != nil {
		log.Fatalf("[ERROR] HttpsProxyServerStop err:%v\n", err)
	}
	log.Printf("[INFO] HttpsProxyServerStop %v stopped\n", Init.GetStringConf("proxy.https.addr"))
}
